import frappe
from frappe import _
from frappe.utils import flt


@frappe.whitelist()
def split_work_order(work_order_name, qty):
    qty = flt(qty)
    doc = frappe.get_doc("Work Order", work_order_name)
    if qty<= 0 or qty >= doc.qty:
        frappe.throw(_("Qty should be more than 0 and less than order qty"))

    doc2 = frappe.copy_doc(doc)
    doc2.qty = doc.qty - qty

    doc1 = doc if doc.docstatus == 0 else frappe.copy_doc(doc)
    doc1.qty = qty
    if doc.docstatus == 1:
        doc.cancel()
        doc1.amended_from = doc.name
        doc1.submit()
    else:
        doc1.save()

    doc2.save()

    return doc1.name

@frappe.whitelist()
def get_exploded_item_oem_code(bom, data = []):    
    bom_item = frappe.qb.DocType('BOM Item')

    exploded_items = frappe.qb.from_(bom_item    
        ).select(bom_item.bom_no, bom_item.item_code, bom_item.oem_code            
        ).where(bom_item.parent == bom
        ).run(as_dict=1)        

    for item in exploded_items:        
        data.append([item.item_code, item.oem_code])
        if item.bom_no:
            get_exploded_item_oem_code(item.bom_no, data)

    return  frappe._dict(data) if data else {}